//
//  AppDelegate.m
//  国学商家管理
//
//  Created by mac on 2018/6/19.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "AppDelegate.h"
#import "TMBaseTabbarContriller.h"
#import "TMLoginController.h"
#import "TMBaseNavgationController.h"
#import <UMShare/UMShare.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AlipaySDK/AlipaySDK.h>
#import "JPUSHService.h"
#import "WXApi.h"
#import "WXApiObject.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
//// 如果需要使用idfa功能所需要引入的头文件（可选）
//#import <AdSupport/AdSupport.h>
#import "TMPushModel.h"
#import "TMSystemsMessController.h"
#import "TMConversationListController.h"
@interface AppDelegate ()<RCIMReceiveMessageDelegate,JPUSHRegisterDelegate,WXApiDelegate,RCIMConnectionStatusDelegate,RCIMUserInfoDataSource>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[UINavigationBar appearance] setBarTintColor:[HXColor hx_colorWithHexRGBAString:@"#05B48D"]];
     [[RCIM sharedRCIM] initWithAppKey:IMClodeAppKey];
    if ([TMUserManager deaufatManager].userModel.token != nil) {
        //判断状态
        [self displayNotiStytle:launchOptions];
        [JPUSHService addTags:[NSSet setWithObject:@([TMUserManager deaufatManager].userModel.uid).description] completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
            
        } seq:1];

    }else{
        [JPUSHService cleanTags:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
            
        } seq:1];
        
    }
    [AMapServices sharedServices].apiKey = AMapAppKey;
    [self displaySharePlatform];
    if ([application
         respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        //注册推送, 用于iOS8以及iOS8之后的系统
        UIUserNotificationSettings *settings = [UIUserNotificationSettings
                                                settingsForTypes:(UIUserNotificationTypeBadge |
                                                                  UIUserNotificationTypeSound |
                                                                  UIUserNotificationTypeAlert)
                                                categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    [self displayJPush:launchOptions];
    self.window.backgroundColor = UIColor.whiteColor;
    return YES;
}

- (void)displaySharePlatform{
    [TMUserManager displayRCConfings];
    [[RCIM sharedRCIM] setReceiveMessageDelegate:self];
    [RCIM sharedRCIM].enableTypingStatus = YES;
    [RCIM sharedRCIM].enableMessageRecall = YES;
    [RCIMClient sharedRCIMClient].logLevel = RC_Log_Level_Info;
    [RCIM sharedRCIM].enabledReadReceiptConversationTypeList =
    @[ @(ConversationType_PRIVATE), @(ConversationType_DISCUSSION), @(ConversationType_GROUP) ];
    
    //开启多端未读状态同步
    [RCIM sharedRCIM].enableSyncReadStatus = YES;
    [RCIM sharedRCIM].connectionStatusDelegate = self;
    //设置显示未注册的消息
    //如：新版本增加了某种自定义消息，但是老版本不能识别，开发者可以在旧版本中预先自定义这种未识别的消息的显示
    [RCIM sharedRCIM].showUnkownMessage = YES;
    [RCIM sharedRCIM].showUnkownMessageNotificaiton = YES;
    [RCIM sharedRCIM].userInfoDataSource= self;
    
    [[UMSocialManager defaultManager] setUmSocialAppkey:UMSociaAppKey];
    [[UMSocialManager defaultManager] openLog:YES];
    
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:UMSociaWechatAppKey appSecret:UMSociaWechatAppSecret redirectURL:@"http://mobile.umeng.com/social"];
    //    /* 设置分享到QQ互联的appID
    //     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
    //     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:UMSociaQQAppKey/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    
    [WXApi registerApp:UMSociaWechatAppKey];

}
//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
//{
//    [WXApi handleOpenURL:url delegate:[PaymentAction sharedPayment]];
//    [UMSocialSnsService handleOpenURL:url];
////    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
////    if (!result) {
////        // 其他如支付等SDK的回调
////    }
//    return YES;
//}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    
    //BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    [WXApi handleOpenURL:url delegate:self];
    [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
        // 其他如支付等SDK的回调
        if ([url.host isEqualToString:@"safepay"]) {
            //跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"result = %@",resultDic);
                if (resultDic && [resultDic objectForKey:@"resultStatus"] && ([[resultDic objectForKey:@"resultStatus"] intValue] == 9000)) {
                    
                    // 发通知带出支付成功结果
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAliReturnSucceedPayNotification" object:resultDic];
                } else {
                    
                    // 发通知带出支付失败结果
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAliReturnFailedPayNotification" object:resultDic];
                }
            }];
        }
        
        if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
            [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"支付宝网页版result = %@",resultDic);
                if (resultDic && [resultDic objectForKey:@"resultStatus"] && ([[resultDic objectForKey:@"resultStatus"] intValue] == 9000)) {
                    
                    // 发通知带出支付成功结果
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAliReturnSucceedPayNotification" object:resultDic];
                } else {
                    
                    // 发通知带出支付失败结果
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAliReturnFailedPayNotification" object:resultDic];
                }
            }];
    }
    return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
//{
//    return [WXApi handleOpenURL:url delegate:self];
//}




#pragma --mark message delegate
- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left{
    dispatch_async(dispatch_get_main_queue(), ^{
    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)//应用在前台
    {
        
        //修改app消息界面的参数
        
    }
    else//应用在后台
    {
        
        int allunread = [[RCIMClient sharedRCIMClient] getTotalUnreadCount];//获取消息数量
        if(allunread > 0)
        {
            
            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:allunread];//修改应用图标上的数字
            //[[NSNotificationCenter defaultCenter] postNotificationName:@"SHOWREDINFORMATIONS" object:nil userInfo:@{@"ismessage":@(11)}];
        }
        
    }
        });
}
//houtai  shi
- (BOOL)onRCIMCustomLocalNotification:(RCMessage *)message withSenderName:(NSString *)senderName{
    return NO;
}
- (BOOL)onRCIMCustomAlertSound:(RCMessage *)message{
    
    return NO;
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    
    NSDictionary *msgDic = [notification.userInfo objectForKey:@"rc"];
    if (msgDic != nil) {
        NSString *targetId = [msgDic objectForKey:@"tId"];//Target ID 。
        RCConversationViewController *chat = [[RCConversationViewController alloc]init];
        chat.conversationType = ConversationType_PRIVATE;
        chat.targetId = targetId;
        [[SPToolSet currentViewController].navigationController pushViewController:chat animated:NO];
    }else{
        TMSystemsMessController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"TMSystemsMessController"];
        vc.isPush = YES;
        [[SPToolSet currentViewController].navigationController pushViewController:vc animated:YES];
    }
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
    NSString *str =  [JPUSHService registrationID];
    [[NSUserDefaults standardUserDefaults] setValue:str forKey:@"registrationID"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    NSString *token =
    [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
                                                           withString:@""]
      stringByReplacingOccurrencesOfString:@">"
      withString:@""]
     stringByReplacingOccurrencesOfString:@" "
     withString:@""];
    
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
    [application registerForRemoteNotifications];
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)(void))completionHandler {
}
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)(void))completionHandler {
}
#endif

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // 取得 APNs 标准信息内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
    TMPushModel *model = [TMPushModel yy_modelWithJSON:userInfo];
    model.alert = userInfo[@"aps"][@"alert"];
    if (application.applicationState == UIApplicationStateActive) {
    
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"推送消息" message:@"" preferredStyle:UIAlertControllerStyleAlert handler:^(UIAlertAction * _Nonnull action) {
            if ([action.title isEqualToString:@"前往>"]) {
                TMSystemsMessController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"TMSystemsMessController"];
                vc.isPush = YES;
                vc.model = model;
                [[SPToolSet currentViewController].navigationController pushViewController:vc animated:YES];
            }
        } cancelButtonTitle:@"取消" otherButtonTitles:@"前往>", nil];
    [[SPToolSet currentViewController] presentViewController:alert animated:YES completion:^{
        
    }];
    }
    
    if (application.applicationState == UIApplicationStateInactive) {
        TMSystemsMessController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"TMSystemsMessController"];
        vc.isPush = YES;
        vc.model = model;
        [[SPToolSet currentViewController].navigationController pushViewController:vc animated:YES];
    }
    
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"收到通知:%@", [self logDic:userInfo]);
    //    [rootViewController addNotificationCount];
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"收到通知:%@", [self logDic:userInfo]);
    // 取得 APNs 标准信息内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
    TMPushModel *model = [TMPushModel yy_modelWithJSON:userInfo];
    model.alert = userInfo[@"aps"][@"alert"];
    
    NSDictionary *msgDic = [userInfo objectForKey:@"rc"];
//    if (application.applicationState == UIApplicationStateActive) {
    
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"推送消息" message:@"" preferredStyle:UIAlertControllerStyleAlert handler:^(UIAlertAction * _Nonnull action) {
            if ([action.title isEqualToString:@"前往>"]) {
                if (msgDic != nil) {
                    TMConversationListController *vc = [[TMConversationListController alloc]init];
                    [[SPToolSet currentViewController].navigationController pushViewController:vc animated:YES];
                }else{
                TMSystemsMessController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"TMSystemsMessController"];
                vc.isPush = YES;
                vc.model = model;
                [[SPToolSet currentViewController].navigationController pushViewController:vc animated:YES];
            }
            }
        } cancelButtonTitle:@"取消" otherButtonTitles:@"前往>", nil];
    [[SPToolSet currentViewController] presentViewController:alert animated:YES completion:^{
        
    }];
    //}
    if (application.applicationState == UIApplicationStateInactive) {
        TMSystemsMessController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"TMSystemsMessController"];
        vc.isPush = YES;
        vc.model = model;
        [[SPToolSet currentViewController].navigationController pushViewController:vc animated:YES];
    }
    
    
    completionHandler(UIBackgroundFetchResultNewData);
}


- (void)showPushmessage_urlVC:(NSString *)message_url infoID: (NSInteger )infoID{
    
    
}

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

- (void)displayJPush:(NSDictionary *)launchOptions{
    //推送
    // Override point for customization after application launch.
    
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:nil];
    
}
-(void)onResp:(BaseResp *)resp {
    if([resp isKindOfClass:[PayResp class]]){
        switch (resp.errCode) {
            case WXSuccess:{
                NSLog(@"支付成功");
                // 发通知带出支付成功结果
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAliReturnSucceedPayNotification" object:resp];
            }
                break;
            default:{
                NSLog(@"支付失败:%d",resp.errCode);
                // 发通知带出支付失败结果
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAliReturnFailedPayNotification" object:resp];
            }
                break;
        }
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    //使用这个方法来释放共享资源，保存用户数据，无效
    //定时器，并存储足够的应用程序状态信息以恢复您的
    //应用程序到其目前的状态，以防它被终止。
    //如果您的应用程序支持后台执行，则调用此方法
    //而不是applicationWillTerminate:当用户退出。
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];//清除本地角标数量为0
    [JPUSHService setBadge:0];//通报服务器,角标数量为0,否则有消息推送,会在之前基础上+1
    [[UIApplication sharedApplication]cancelAllLocalNotifications];//取消任何通知标志
    
}
- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status {
    NSLog(@"%ld", status);
    if (status == ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT) {
        [TMUserManager deaufatManager].userModel.token = nil;
        [TMUserManager deaufatManager].userModel.rongyun = nil;
        [[TMUserManager deaufatManager] updateUserModel:[TMUserManager deaufatManager].userModel];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"kUSER_INFOR_KEY"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[RCIM sharedRCIM] logout];
        SHOW_LOGIN_ALERT;
        [JPUSHService cleanTags:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
            
        } seq:1];
        
    }
}
- (void)displayPushVC:(UILocalNotification *)notification OR:(NSDictionary *)dic{
    if (notification) {
        NSDictionary *msgDic = [notification.userInfo objectForKey:@"rc"];
        if (msgDic != nil) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SHOWREDINFORMATIONS" object:nil userInfo:@{@"ismessage":@(0)}];
            TMConversationListController *vc = [[TMConversationListController alloc]init];
            [[SPToolSet currentViewController].navigationController pushViewController:vc animated:YES];
        }else{
            TMSystemsMessController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"TMSystemsMessController"];
            vc.isPush = YES;
            //vc.model = model;
            [[SPToolSet currentViewController].navigationController pushViewController:vc animated:YES];
        }
    }
    if (dic) {
        NSDictionary *msgDic = [dic objectForKey:@"rc"];
//        BOOL messageType = [dic[@"push_type"] boolValue];
        if (msgDic != nil) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SHOWREDINFORMATIONS" object:nil userInfo:@{@"ismessage":@(0)}];
            TMConversationListController *vc = [[TMConversationListController alloc]init];
            [[SPToolSet currentViewController].navigationController pushViewController:vc animated:YES];
        }else{
            //[JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
            TMSystemsMessController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"TMSystemsMessController"];
            vc.isPush = YES;
            //vc.model = model;
            [[SPToolSet currentViewController].navigationController pushViewController:vc animated:YES];
        }
    }
    
    
}
- (void)displayNotiStytle:(NSDictionary *)launchOptions{
    UILocalNotification *notification = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
    NSDictionary *dic = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
    if (notification) {
        [self displayPushVC:notification OR:nil];
    }
    if (dic) {
        [self displayPushVC:nil OR:dic];
    }
}
@end
